<!-- 编辑弹窗 -->
<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    :lock-scroll="false"
    :title="
      isUpdate
        ? '为[' + form.campaignName + ']设置单元推广地域'
        : '设置单元推广地域'
    "
    :visible="visible"
    class="ele-dialog-view"
    custom-class="ele-dialog-form"
    width="756px"
    @closed="closed"
    @open="open"
    @opened="opened"
    @update:visible="updateVisible"
  >
    <el-form ref="form" :model="form" label-width="50px">
      <el-form-item label="地域:">
        <template>
          <span>{{ selectedDataTitle }}</span>
          <div
            class="custom-tree-container"
            style="height: 400px; margin-top: 6px"
          >
            <div
              :style="{
                'border-radius': '4px',
                border: '1px solid #ededed',
                position: 'absolute',
                'pointer-events': leftDisabled ? 'none' : '',
                opacity: leftDisabled ? '.7' : '1.0',
              }"
            >
              <div style="height: 36px; border-bottom: 1px solid #ededed">
                <span style="margin-left: 10px"
                  >可选省市({{ sourceDataLen }})</span
                >
                <span style="position: absolute; left: 138px">
                  <el-checkbox v-model="leftSelectValue" @change="leftSelectAll"
                    >全选/反选</el-checkbox
                  >
                </span>
              </div>
              <el-input
                v-model="leftFilterText"
                clearable
                placeholder="输入关键字进行过滤"
                style="width: 334px"
              >
              </el-input>
              <div
                style="
                  margin-top: 0px;
                  width: 332px;
                  overflow-y: auto;
                  height: 336px;
                  border-top: 1px solid #ededed;
                "
              >
                <el-tree
                  ref="leftTree"
                  :check-on-click-node="true"
                  :data="sourceData"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNodeMethod"
                  node-key="id"
                  show-checkbox
                  @check="leftCheck"
                >
                  <span slot-scope="{ node }" class="custom-tree-node">
                    <span>{{ node.label }}</span>
                  </span>
                </el-tree>
              </div>
            </div>

            <div
              style="
                position: absolute;
                left: 345px;
                border-radius: 4px;
                border: 1px solid #ededed;
              "
            >
              <div v-if="!leftDisabled">
                <div style="height: 36px; border-bottom: 1px solid #ededed">
                  <span style="margin-left: 10px"
                    >已选省市({{ selectedDataLen }})</span
                  >
                  <span style="position: absolute; right: 10px">出价系数</span>
                  <span
                    style="
                      position: absolute;
                      left: 226px;
                      color: rgb(0, 82, 204);
                      cursor: pointer;
                    "
                    @click="clearSelectedData"
                    >清空</span
                  >
                </div>
                <el-input
                  v-model="rightFilterText"
                  clearable
                  placeholder="输入关键字进行过滤"
                  style="width: 334px"
                >
                </el-input>
              </div>
              <div v-if="leftDisabled">
                <div style="height: 36px; border-bottom: 1px solid #ededed">
                  <span style="margin-left: 10px"
                    >已选地域({{ priceFactorLen }})列</span
                  >
                  <span style="position: absolute; right: 12px">出价系数</span>
                </div>
                <el-input
                  v-model="priceFactor"
                  clearable
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  placeholder="范围:0.1~10"
                  style="width: 230px; border-right: 1px solid #ededed"
                >
                </el-input>
                <div>
                  <el-button
                    style="
                      position: absolute;
                      top: 36px;
                      width: 52px;
                      height: 38px;
                      left: 228px;
                    "
                    @click="setPriceFactor"
                    >应用
                  </el-button>
                  <el-button
                    style="
                      position: absolute;
                      top: 36px;
                      width: 52px;
                      height: 38px;
                      left: 271px;
                    "
                    @click="cancelPriceFactor"
                    >取消
                  </el-button>
                </div>
              </div>
              <div
                style="
                  margin-top: 0px;
                  width: 332px;
                  overflow-y: auto;
                  height: 336px;
                  border-top: 1px solid #ededed;
                "
              >
                <el-tree
                  ref="rightTree"
                  :check-on-click-node="true"
                  :data="selectedData"
                  :default-expanded-keys="defaultExpandedKeys"
                  :expand-on-click-node="true"
                  :filter-node-method="filterNodeMethod"
                  node-key="id"
                  show-checkbox
                  @check="openPriceFactor"
                >
                  <span slot-scope="{ node, data }" class="custom-tree-node">
                    <span>{{ node.label }}</span>
                    <span style="position: absolute; right: 42px">
                      <el-link type="primary">{{ data.priceFactor }}</el-link>
                    </span>
                    <span
                      style="position: absolute; right: 12px"
                      @click="() => removeSelecte(node, data)"
                    >
                      <i class="el-icon-close"></i>
                    </span>
                  </span>
                </el-tree>
              </div>
            </div>
          </div>
        </template>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save"
        >确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import baiduRegion from "@/assets/json/json.json";

export default {
  name: "feedCampaignEdit",
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
  },

  data() {
    return {
      // 左侧禁止
      leftDisabled: false,
      // 左侧已选标题
      selectedDataTitle: "推广地域",
      // 左侧筛选
      leftFilterText: "",
      // 左侧全选
      leftSelectValue: false,
      // 左侧源数据
      sourceData: baiduRegion,
      // 左侧默认勾选节点
      defaultCheckedKeys: [],
      // 左侧源数据长度
      sourceDataLen: 0,
      // 右侧筛选
      rightFilterText: "",
      // 右侧选中数据
      selectedData: [],
      // 右侧选中数据长度
      selectedDataLen: 0,
      // 右侧默认展开节点
      defaultExpandedKeys: [],
      // 右侧出价金额
      priceFactor: "",
      // 右侧已选出价节点数
      priceFactorLen: 0,
      // 表单数据
      form: Object.assign({}, this.data),
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
    };
  },

  watch: {
    data() {
      if (this.data.id) {
        this.form = Object.assign({}, this.data);
        this.isUpdate = true;
        return;
      }

      if (this.data.ids) {
        this.isUpdate = false;
        this.form = Object.assign({}, this.data);
        return;
      }

      this.form = {};
      this.isUpdate = false;
    },
    leftFilterText(val) {
      this.$refs.leftTree.filter(val);
    },
    rightFilterText(val) {
      this.$refs.rightTree.filter(val);
    },
  },

  methods: {
    /* Dialog 关闭动画结束时的回调*/
    closed() {
      //左侧禁止
      this.leftDisabled = false;
      //左侧已选标题
      this.selectedDataTitle = "推广地域";
      //左侧筛选
      this.leftFilterText = "";
      //左侧全选
      this.leftSelectValue = false;
      //左侧源数据长度
      this.sourceDataLen = 0;
      //右侧筛选
      this.rightFilterText = "";
      //右侧选中数据
      this.selectedData = [];
      //右侧选中数据长度
      this.selectedDataLen = 0;
      //右侧默认展开节点
      this.defaultExpandedKeys = [];
      //右侧出价金额
      this.priceFactor = "";
      //右侧已选出价节点数
      this.priceFactorLen = 0;
    },

    /* Dialog 打开的回调*/
    open() {
      if (this.$refs.leftTree && this.form.id) {
        this.$refs.leftTree.setCheckedKeys(this.form.defaultCheckedKeys);
        this.setSelectedData();
      }
    },

    /*Dialog 打开动画结束时的回调*/
    opened() {
      if (this.$refs.leftTree && this.form.id) {
        this.$refs.leftTree.setCheckedKeys(this.form.defaultCheckedKeys);
        this.setSelectedData();
      }
    },

    /* 左侧全选 */
    leftSelectAll(obj) {
      if (obj) {
        this.$refs.leftTree.setCheckedNodes(baiduRegion);
      } else {
        this.$refs.leftTree.setCheckedKeys([]);
      }
      this.setSelectedData();
    },

    /* 左侧节点点击*/
    leftCheck() {
      this.setSelectedData();
    },

    /* 获取左侧选择节点*/
    setSelectedData() {
      let labelArray = [];
      let provinceKeys = [];
      const checkedNodes = this.$refs.leftTree.getCheckedNodes(true, true);
      for (let i = 0; i < checkedNodes.length; i++) {
        labelArray.push(checkedNodes[i].label);
        if (checkedNodes[i].pid > 0) {
          if (provinceKeys.indexOf(checkedNodes[i].pid) === -1) {
            provinceKeys.push(checkedNodes[i].pid);
          }
        }
      }
      const provinceList = [
        { label: "广东", id: 4000, children: [], priceFactor: "-", pid: 0 },
        { label: "福建", id: 5000, children: [], priceFactor: "-", pid: 0 },
        { label: "海南", id: 8000, children: [], priceFactor: "-", pid: 0 },
        { label: "安徽", id: 9000, children: [], priceFactor: "-", pid: 0 },
        { label: "贵州", id: 10000, children: [], priceFactor: "-", pid: 0 },
        { label: "甘肃", id: 11000, children: [], priceFactor: "-", pid: 0 },
        { label: "广西", id: 12000, children: [], priceFactor: "-", pid: 0 },
        { label: "河北", id: 13000, children: [], priceFactor: "-", pid: 0 },
        { label: "河南", id: 14000, children: [], priceFactor: "-", pid: 0 },
        { label: "黑龙江", id: 15000, children: [], priceFactor: "-", pid: 0 },
        { label: "湖北", id: 16000, children: [], priceFactor: "-", pid: 0 },
        { label: "湖南", id: 17000, children: [], priceFactor: "-", pid: 0 },
        { label: "吉林", id: 18000, children: [], priceFactor: "-", pid: 0 },
        { label: "江苏", id: 19000, children: [], priceFactor: "-", pid: 0 },
        { label: "江西", id: 20000, children: [], priceFactor: "-", pid: 0 },
        { label: "辽宁", id: 21000, children: [], priceFactor: "-", pid: 0 },
        { label: "内蒙古", id: 22000, children: [], priceFactor: "-", pid: 0 },
        { label: "宁夏", id: 23000, children: [], priceFactor: "-", pid: 0 },
        { label: "青海", id: 24000, children: [], priceFactor: "-", pid: 0 },
        { label: "山东", id: 25000, children: [], priceFactor: "-", pid: 0 },
        { label: "山西", id: 26000, children: [], priceFactor: "-", pid: 0 },
        { label: "陕西", id: 27000, children: [], priceFactor: "-", pid: 0 },
        { label: "四川", id: 28000, children: [], priceFactor: "-", pid: 0 },
        { label: "西藏", id: 29000, children: [], priceFactor: "-", pid: 0 },
        { label: "新疆", id: 30000, children: [], priceFactor: "-", pid: 0 },
        { label: "云南", id: 31000, children: [], priceFactor: "-", pid: 0 },
        { label: "浙江", id: 32000, children: [], priceFactor: "-", pid: 0 },
      ];
      for (let i = 0; i < provinceList.length; i++) {
        if (provinceKeys.indexOf(provinceList[i].id) > -1) {
          checkedNodes.push(provinceList[i]);
        }
      }
      if (labelArray.length === 0) {
        this.clearSelectedData();
        this.selectedDataTitle = "未选择地域（请至少选择一个地域）";
      } else {
        this.selectedDataTitle =
          labelArray.slice(-5).join("，") +
          "等共" +
          labelArray.length +
          "个区域";
      }
      this.selectedDataLen = labelArray.length;
      this.sourceDataLen = 370 - labelArray.length;
      if (this.sourceDataLen > 0) {
        this.leftSelectValue = false;
      }
      this.selectedData = this.getChildrenList(checkedNodes, 0);
    },

    /* 打开出价设置 */
    openPriceFactor() {
      const checkedNodes = this.$refs.rightTree.getCheckedNodes();
      if (checkedNodes.length === 0) {
        this.leftDisabled = false;
        return;
      }
      this.priceFactorLen = 0;
      for (let i = 0; i < checkedNodes.length; i++) {
        if (checkedNodes[i].children.length === 0) {
          this.priceFactorLen++;
        }
      }
      this.priceFactor = "";
      this.leftDisabled = true;
    },

    /* 设置当前出价*/
    setPriceFactor() {
      if (this.priceFactor > 10) {
        this.$message.error("出价系数, 最小0.1元最大10元.");
        return;
      }
      let setPriceArrayList = [];
      const checkedNodes = this.$refs.rightTree.getCheckedNodes();
      for (let i = 0; i < checkedNodes.length; i++) {
        for (const item of checkedNodes[i].children) {
          setPriceArrayList.push(item.id);
        }
        setPriceArrayList.push(checkedNodes[i].id);
      }
      if (setPriceArrayList.length > 0) {
        setPriceArrayList = this.arrUnique(setPriceArrayList);
        for (let i = 0; i < this.selectedData.length; i++) {
          for (let ii = 0; ii < this.selectedData[i].children.length; ii++) {
            if (
              setPriceArrayList.indexOf(this.selectedData[i].children[ii].id) >
              -1
            ) {
              this.selectedData[i].children[ii].priceFactor = this.priceFactor;
            }
          }
          if (this.selectedData[i].children.length === 0) {
            if (setPriceArrayList.indexOf(this.selectedData[i].id) > -1) {
              this.selectedData[i].priceFactor = this.priceFactor;
            }
          }
        }
      }
      this.$refs.rightTree.setCheckedKeys([]);
      this.leftDisabled = false;
    },

    /* 取消出价设置*/
    cancelPriceFactor() {
      this.priceFactorLen = 0;
      this.leftDisabled = false;
      this.$refs.rightTree.setCheckedKeys([]);
    },

    /* 删除右边选中*/
    removeSelecte(node, data) {
      let deleteArray = [];
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      let checkedNodes = this.$refs.leftTree.getCheckedNodes();
      for (let i = 0; i < checkedNodes.length; i++) {
        if (deleteArray.indexOf(checkedNodes[i].id) === -1) {
          deleteArray.push(checkedNodes[i].id);
        }
        for (const item of checkedNodes[i].children) {
          if (deleteArray.indexOf(item.id) === -1) {
            deleteArray.push(item.id);
          }
        }
      }
      let findId = deleteArray.indexOf(children[index].id);
      if (findId > -1) {
        deleteArray.splice(findId, 1);
      }
      if (children[index].pid > 0) {
        let findPid = deleteArray.indexOf(children[index].pid);
        if (findPid > -1) {
          deleteArray.splice(findPid, 1);
        }
      }
      if (children[index].children.length > 0) {
        for (const item of children[index].children) {
          let deleteId = deleteArray.indexOf(item.id);
          if (deleteId > -1) {
            deleteArray.splice(deleteId, 1);
          }
        }
      }
      this.$refs.leftTree.setCheckedKeys(deleteArray);
      this.defaultExpandedKeys = [data.pid];
      children.splice(index, 1);
      this.setSelectedData();
    },

    /* 清除选择数据 */
    clearSelectedData() {
      this.selectedData = [];
      this.sourceDataLen = 0;
      this.selectedDataLen = 0;
      this.leftSelectValue = false;
      this.$refs.leftTree.setCheckedKeys([]);
      this.selectedDataTitle = "未选择地域（请至少选择一个地域）";
    },

    /* 对树节点进行筛选操作 */
    filterNodeMethod(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    /* 数组去重复 */
    arrUnique(arr) {
      const onlyUnique = (value, index, self) => {
        return self.indexOf(value) === index;
      };
      return arr.filter(onlyUnique);
    },

    // 无限极分类递归
    getChildrenList(arr, pid = 0) {
      let array = [];
      for (const item of arr) {
        if (item.pid === pid) {
          item.children = this.getChildrenList(arr, item.id);
          array.push(item);
        }
      }
      return array;
    },

    /* 确定编辑 */
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.form.regionTarget = JSON.stringify(this.selectedData);
          this.$http
            .put("/FeedUnit/updateRegionTarget", this.form)
            .then((res) => {
              this.loading = false;
              if (res.data.code === 0) {
                if (res.data.data) {
                  let _message = res.data.data.join("<br/>");
                  this.$message({
                    dangerouslyUseHTMLString: true,
                    message: _message,
                    duration: 5000,
                    iconClass: "icon-ex",
                    type: _message.indexOf("code") === -1 ? "success" : "error",
                  });
                } else {
                  this.$message({ type: "success", message: res.data.msg });
                }
                this.updateVisible(false);
                this.$emit("done");
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit("update:visible", value);
    },
  },
};
</script>

<style scoped>
.ele-dialog-view /deep/ .el-dialog__body {
  padding: 10px 8px !important;
}

.custom-tree-container >>> .el-input__inner {
  border-radius: 0;
  border: none;
}

.custom-tree-container >>> .el-button--medium {
  padding: 10px 0;
  border-radius: 0;
}

.custom-tree-container .el-tree {
  top: 4px;
}
</style>
